package com.hotel.config.rabbitmq.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class CutTopConfig {
    /**
     * 订单削峰限流业务
     */
    // 削峰限流交换机
    public static final String CUTTOP_ORDER_EXCHANGE = "cuttop.order.exchange";
    // 削峰限流队列
    public static final String CUTTOP_ORDER_QUEUE = "cuttop.order.queue";
    // 路由key
    public static final String CUTTOP_ORDER_ROUTER_KEY = "cuttop.order.router.key";
    // 削峰限流死信交换机
    public static final String DEAD_CUTTOP_ORDER_EXCHANGE = "dead.cuttop.order.exchange";
    // 削峰限流死信队列
    public static final String DEAD_CUTTOP_ORDER_QUEUE = "dead.cuttop.order.queue";
    // 死信路由key
    public static final String DEAD_CUTTOP_ORDER_ROUTER_KEY = "dead.cuttop.order.router.key";

    // 削峰限流交换机
    @Bean("cuttopExchange")
    public DirectExchange cuttopExchange(){
        return new DirectExchange(CUTTOP_ORDER_EXCHANGE,true,false);
    }

    // 削峰限流队列
    @Bean("cuttopQueue")
    public Queue cuttopQueue(){
        Map<String,Object> map = new HashMap<>();
        map.put("x-message-ttl",5*1000); // 过期时间5s
        map.put("x-max-length",100);    // 队列最大长度
        map.put("x-dead-letter-exchange",DEAD_CUTTOP_ORDER_EXCHANGE); // 死信交换机
        map.put("x-dead-letter-routing-key",DEAD_CUTTOP_ORDER_ROUTER_KEY); // 死信路由
        return new Queue(CUTTOP_ORDER_QUEUE,true,false,false);
    }

    // 削峰限流绑定
    @Bean("cuttopBind")
    public Binding cuttopBind(@Qualifier("cuttopExchange") DirectExchange directExchange,
                              @Qualifier("cuttopQueue") Queue queue){
        return BindingBuilder.bind(queue).to(directExchange).with(CUTTOP_ORDER_ROUTER_KEY);
    }

    // 死信交换机
    @Bean("deadCuttopExchange")
    public DirectExchange deadExchange() {
        return new DirectExchange(DEAD_CUTTOP_ORDER_EXCHANGE,true,false);
    }

    // 死信队列
    @Bean("deadCuttopQueue")
    public Queue deadQueue() {
        return new Queue(DEAD_CUTTOP_ORDER_QUEUE,true,false,false);
    }

    // 死信绑定
    @Bean("deadCuttopBind")
    public Binding bindingDeadQueue(@Qualifier("deadCuttopQueue") Queue queue,
                                    @Qualifier("deadCuttopExchange") DirectExchange
                                            directExchange) {
        return BindingBuilder.bind(queue).to(directExchange).with(DEAD_CUTTOP_ORDER_ROUTER_KEY);
    }
}
